package com.cloud.bssp.nio.bytebuffer;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description： 分散写
 * @author：weirx
 * @date：2021/11/2 18:08
 * @version：3.0
 */
public class GatheringWrite {

    public static void main(String[] args) throws Exception {
        RandomAccessFile file = new RandomAccessFile("C:\\Users\\P50\\Desktop\\text.txt", "rw");
        FileChannel channel = file.getChannel();
        ByteBuffer d = ByteBuffer.allocate(4);
        ByteBuffer e = ByteBuffer.allocate(4);
        channel.position(11);

        d.put(new byte[]{'f', 'o', 'u', 'r'});
        e.put(new byte[]{'f', 'i', 'v', 'e'});
        d.flip();
        e.flip();
        System.out.println(print(d));
        System.out.println(print(e));
        channel.write(new ByteBuffer[]{d, e});
    }

    static String print(ByteBuffer b) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < b.limit(); i++) {
            stringBuilder.append((char) b.get(i));
        }
        return stringBuilder.toString();
    }
}
